<!-- filepath: src/components/ChartIndex.vue -->
<template>
  <!-- 移除container-type样式，使用Tailwind响应式类 -->
  <div class="max-w-[100vw] mx-auto bg-gray-800 shadow-2xl overflow-hidden text-white font-sans p-0 m-0 md:p-4">
    <!-- 顶部导航 -->
    <div class="bg-gray-900 px-3 sm:px-4 py-3 border-b border-gray-700 sm:px-6">
      <div class="flex justify-between items-center flex-wrap gap-3">
        <div class="flex items-center gap-3">
          <div class="flex items-center gap-3">
          <h1 class="text-base sm:text-lg md:text-xl font-bold flex items-center">
            <i class="fas fa-running mr-2 text-blue-400"></i> 跑步数据分析
          </h1>
          <button data-html2canvas-ignore @click="captureScreenshot" class="px-2 py-1 rounded-lg bg-gray-700 hover:bg-gray-600 text-gray-300 transition text-xs sm:text-sm flex items-center">
              <i class="fas fa-camera mr-1"></i>截屏
          </button>
        </div>
        </div>
        <!-- 导航按钮组 -->
        <div data-html2canvas-ignore class="flex space-x-1 sm:space-x-2 sm:w-auto justify-center sm:justify-end">
          <button class="px-2 py-1 rounded-lg bg-gray-700 hover:bg-gray-600 text-gray-300 transition text-xs sm:text-sm flex-1 sm:flex-none sm:min-w-0">
            <i class="fas fa-chart-bar mr-1 hidden sm:inline"></i><span class="hidden sm:inline">统计</span>
          </button>
          <button class="px-2 py-1 rounded-lg bg-gray-700 hover:bg-gray-600 text-gray-300 transition text-xs sm:text-sm">
            <i class="fas fa-flag mr-1 hidden sm:inline"></i><span class="hidden sm:inline">计圈</span>
          </button>
          <button class="px-2 py-1 rounded-lg bg-blue-600 hover:bg-blue-700 text-white transition text-xs sm:text-sm">
            <i class="fas fa-chart-line mr-1 hidden sm:inline"></i><span class="hidden sm:inline">图表</span>
          </button>
          <button class="px-2 py-1 rounded-lg bg-gray-700 hover:bg-gray-600 text-gray-300 transition text-xs sm:text-sm">
            <i class="fas fa-shoe-prints mr-1 hidden sm:inline"></i><span class="hidden sm:inline">装备</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="p-4 sm:p-6">
      <!-- 活动基本信息 -->
      <div class="bg-gray-750 p-3 sm:p-6 rounded-lg mb-4 sm:mb-6 border border-gray-700">
        <div>
          <h2 class="text-xl sm:text-2xl font-extrabold text-white mb-2">{{ activityName }}</h2>
          <div class="text-gray-300 text-sm sm:text-base mb-4">
            <pre class="whitespace-pre-wrap">{{ description }}</pre>
            <!-- {{ description }} -->
          </div>
        </div>
        <!-- 使用响应式网格：移动端1列，平板2列，桌面3列 -->
        <div class="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-4 gap-2 sm:gap-4 text-xs sm:text-md whitespace-nowrap">
          <div class="flex items-center space-x-2">
            <i class="fas fa-calendar-alt text-blue-400"></i>
            <span class="font-semibold">时间:</span>
            <span class="font-bold text-white truncate">{{ startTimeLocal ? startTimeLocal.replace('T', ' ').slice(0, 16) : '--' }}</span>
          </div>
          <div class="flex items-center space-x-2">
            <i class="fas fa-ruler text-green-400"></i>
            <span class="font-semibold">距离：</span>
            <span class="font-bold text-white">{{ (totalDistance / 1000).toFixed(2) }} 公里</span>
          </div>
          <div class="flex items-center space-x-2">
            <i class="fas fa-stopwatch text-yellow-400"></i>
            <span class="font-semibold">用时：</span>
            <span class="font-bold text-white">{{ formatDuration(totalDuration) }}</span>
          </div>
          <div class="flex items-center space-x-2">
            <i class="fas fa-heartbeat text-red-400"></i>
            <span class="font-semibold">平均心率：</span>
            <span class="font-bold text-white">{{ avgHr }} bpm</span>
          </div>
          <div class="flex items-center space-x-2">
            <i class="fas fa-tachometer-alt text-blue-400"></i>
            <span class="font-semibold">平均配速：</span>
            <span class="font-bold text-white">{{ avgPace }} /公里</span>
          </div>
          <div class="flex items-center space-x-2">
            <i class="fas fa-bolt text-yellow-400"></i>
            <span class="font-semibold">最大心率：</span>
            <span class="font-bold text-white">{{ maxHr }} bpm</span>
          </div>
          <div class="flex items-center space-x-2">
            <i class="fas fa-trophy text-orange-400"></i>
            <span class="font-semibold">最佳配速：</span>
            <span class="font-bold text-white">{{ bestPace }} /公里</span>
          </div>
        </div>
      </div>

      <!-- 时间/距离概览 -->
      <div class="bg-gray-750 p-5 rounded-lg mb-6 border border-gray-700">
        <div class="flex justify-between items-center">
          <div>
            <h2 class="text-gray-400 font-semibold text-sm uppercase tracking-wider">时间</h2>
            <p class="text-2xl font-bold text-white mt-1">{{ formatDuration(totalDuration) }}</p>
          </div>
          <div class="text-right">
            <h2 class="text-gray-400 font-semibold text-sm uppercase tracking-wider">距离</h2>
            <p class="text-2xl font-bold text-white mt-1">{{ (totalDistance / 1000).toFixed(2) }} 公里</p>
          </div>
        </div>
      </div>

      <!-- 配速图表 -->
      <div class="bg-gray-800 border border-gray-700 rounded-xl p-4 mb-4 sm:p-5 sm:mb-6">
        <div class="flex justify-between items-start mb-4 sm:mb-6 flex-wrap gap-4">
          <div>
            <h3 class="text-lg sm:text-xl font-bold text-blue-400 flex items-center">
              <i class="fas fa-tachometer-alt mr-2"></i>配速
            </h3>
          </div>
          <!-- 配速图表右上角 -->
          <div class="flex space-x-4 sm:space-x-8 w-full sm:w-auto justify-between sm:justify-end">
            <div class="text-right flex-1 sm:flex-none min-w-[80px]">
              <p class="text-gray-400 text-xs sm:text-sm">平均</p>
              <p class="font-bold text-white text-base sm:text-lg">{{ avgPace }}<span class="text-gray-500 text-xs sm:text-sm"> /公里</span></p>
            </div>
            <div class="text-right flex-1 sm:flex-none min-w-[80px]">
              <p class="text-gray-400 text-xs sm:text-sm">最佳</p>
              <p class="font-bold text-white text-base sm:text-lg">{{ bestPace }}<span class="text-gray-500 text-xs sm:text-sm"> /公里</span></p>
            </div>
          </div>
        </div>
        <!-- 使用响应式高度 -->
        <div class="h-[220px] sm:h-[280px] md:h-[350px] lg:h-[400px] w-full">
          <VChart :option="paceOption" autoresize />
        </div>
      </div>
      
      <!-- 心率图表 -->
      <div class="bg-gray-800 border border-gray-700 rounded-xl p-4">
        <div class="flex justify-between items-start mb-4 sm:mb-6">
          <div>
            <h3 class="text-xl font-bold text-red-400 flex items-center">
              <i class="fas fa-heartbeat mr-2"></i>心率
            </h3>
          </div>
          <!-- 心率图表右上角 -->
          <div class="flex space-x-8">
            <div class="text-right">
              <p class="text-gray-400 text-sm">平均</p>
              <p class="font-bold text-white text-lg">{{ avgHr }}<span class="text-gray-500 text-sm"> bpm</span></p>
            </div>
            <div class="text-right">
              <p class="text-gray-400 text-sm">最大</p>
              <p class="font-bold text-white text-lg">{{ maxHr }}<span class="text-gray-500 text-sm"> bpm</span></p>
            </div>
          </div>
        </div>
        <!-- 使用Tailwind响应式高度 -->
        <div class="h-[250px] sm:h-[300px] md:h-[400px] w-full">
          <VChart :option="hrOption" autoresize />
        </div>
      </div>

      <!-- 每公里数据表格 -->
      <div class="bg-gray-800 border border-gray-700 rounded-xl p-4 mt-4 sm:p-5 sm:mt-6 overflow-hidden">
        <h3 class="text-lg sm:text-xl font-bold text-green-400 flex items-center mb-4 sm:mb-6">
          <i class="fas fa-list-ol mr-2"></i>每公里详细数据
        </h3>
        <div class="overflow-x-auto -mx-2 sm:mx-0 px-2 sm:px-0">
          <table class="min-w-full divide-y divide-gray-700 text-xs sm:text-sm">
            <thead>
              <tr>
                <th class="px-2 py-2 bg-gray-750 text-left font-bold text-gray-300 uppercase tracking-wider">圈数</th>
                <th class="px-2 py-2 bg-gray-750 text-left font-bold text-gray-300 uppercase tracking-wider">时间</th>
                <th class="px-2 py-2 bg-gray-750 text-left font-bold text-gray-300 uppercase tracking-wider">平均配速</th>
                <th class="px-2 py-2 bg-gray-750 text-left font-bold text-gray-300 uppercase tracking-wider sm:table-cell">心率</th>
                <th class="px-2 py-2 bg-gray-750 text-left font-bold text-gray-300 uppercase tracking-wider lg:table-cell">步频</th>
                <th class="px-2 py-2 bg-gray-750 text-left font-bold text-gray-300 uppercase tracking-wider xl:table-cell">步幅</th>
              </tr>
            </thead>
            <tbody class="bg-gray-800 divide-y divide-gray-700">
              <tr v-for="(lap, index) in lapData" :key="index" class="hover:bg-gray-750 transition-colors duration-150">
                <td class="px-2 py-2 whitespace-nowrap font-bold text-gray-300">第{{ index + 1 }}圈</td>
                <td class="px-2 py-2 whitespace-nowrap font-bold" :class="getPaceColor(lap.duration)">{{ lap.duration }}</td>
                <td class="px-2 py-2 whitespace-nowrap font-bold" :class="getPaceColor(lap.pace)">{{ lap.pace }}</td>
                <td class="px-2 py-2 whitespace-nowrap font-bold sm:table-cell" :class="getHrColor(lap.hr)">{{ lap.hr }} bpm</td>
                <td class="px-2 py-2 whitespace-nowrap font-bold text-gray-300 lg:table-cell">{{ lap.cadence }} 步/分</td>
                <td class="px-2 py-2 whitespace-nowrap font-bold text-gray-300 xl:table-cell">{{ lap.stride }} cm</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- 新增地图模块 -->
      <div v-show="isOutside" class="bg-gray-800 border border-gray-700 rounded-xl p-4 mt-4 sm:p-5 sm:mt-6 overflow-hidden">
        <h3 class="text-lg sm:text-xl font-bold text-orange-400 flex items-center mb-4 sm:mb-6">
          <i class="fas fa-list-ol mr-2"></i>活动轨迹
        </h3>
        <div class="overflow-x-auto -mx-4 sm:mx-0 px-4 sm:px-0">
          <div id="baidu-map" class="w-full h-[300px] sm:h-[400px] rounded-lg shadow-[0_2px_10px_rgba(0,0,0,0.1)]"></div>
        </div>
      </div>
      
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router'
import '@/components/ActivityChart.vue'
import VChart from 'vue-echarts'
// 添加格式化函数导入
import { formatDurationShort, formatPace } from '@/utils/formatters'

const route = useRoute()
const activityId = route.params.activityId || 'default'

// 响应式数据
const activityName = ref('')
const description = ref('')
const startTimeLocal = ref('')
const distance = ref(0)
const averageHR = ref(0)
const totalDuration = ref(0)
const totalDistance = ref(0)
const paceW = ref(0)
const avgPace = ref('--')
const bestPace = ref('--')
const avgHr = ref('--')
const maxHr = ref('--')
const lapData = ref([]) // 添加每公里数据数组
const isOutside = ref(true)

// 图表数据
const paceOption = ref({})
const hrOption = ref({})

function formatDuration(sec) {
  const m = Math.floor(sec / 60)
  const s = Math.round(sec % 60)
  const h = Math.floor(m / 60)
  return h > 0
    ? `${h}:${(m % 60).toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
    : `${m}:${s.toString().padStart(2, '0')}`
}
function formatPace1(speed) {
  if (!speed) return '--'
  // 从米/秒转换为分/公里配速
  const pace = 1000 / (speed * 60)
  const min = Math.floor(pace)
  const sec = Math.round((pace - min) * 60)
  return `${min}:${sec.toString().padStart(2, '0')}`
}
function formatDurationShort1(sec) {
  const m = Math.floor(sec / 60)
  const s = Math.round(sec % 60)
  return `${m}:${s.toString().padStart(2, '0')}`
}

// 详细数据提取函数
function extractDetailSeries(detailData, keys = []) {
  if (!detailData || !detailData.metricDescriptors || !detailData.activityDetailMetrics) return {}

  // 1. 建立 key 到 metricsIndex 的映射
  const keyIndexMap = {}
  detailData.metricDescriptors.forEach(d => {
    keyIndexMap[d.key] = d.metricsIndex
  })

  // 2. 提取每个指标的原始数据
  const result = {}
  keys.forEach(key => {
    const idx = keyIndexMap[key]
    if (idx === undefined) {
      result[key] = []
      return
    }
    // 处理单位换算
    const factor = detailData.metricDescriptors[idx]?.unit?.factor ?? 1
    result[key] = detailData.activityDetailMetrics.map(m => {
      const v = m.metrics[idx]
      return v == null ? null : (factor && factor !== 1 ? v * factor : v)
    })
  })

  // 3. 时间戳（秒）
  const timeIdx = keyIndexMap['directTimestamp']
  result['time'] = detailData.activityDetailMetrics.map(m => {
    // 转为相对秒数
    const t = m.metrics[timeIdx]
    return t ? Math.round((t - detailData.activityDetailMetrics[0].metrics[timeIdx]) / 1000) : 0
  })

  return result
}


// 添加条件颜色判断函数
function getPaceColor(value) {
  // 现在value已经是格式化后的字符串如"5:00"
  const [minutes, seconds] = value.split(':').map(Number);
  const totalMinutes = minutes + seconds / 60;
  return totalMinutes >= 5 ? 'text-green-500' : 'text-gray-300';
}

function getHrColor(hr) {
  // 确保心率是数字类型
  const heartRate = Number(hr)
  let currentColor = 'text-gray-300'
  if (heartRate <= 130) {
  } else if (heartRate > 130 && heartRate <= 135) {
    currentColor = 'text-yellow-500'
  } else if (heartRate > 135 && heartRate <= 140) {
    currentColor = 'text-red-500'
  } else if (heartRate > 140) {
    currentColor = 'text-blue-500'
  }
  return currentColor
  // return hrKv[heartRate] || 'text-gray-300'
  // return heartRate > 130 && heartRate < 135 ? 'text-yellow-500' : 'text-gray-300'
  // return heartRate > 130 ? heartRate > 135 ? 'text-yellow-500' : 'text-red-500' : 'text-gray-300';

}

// 新增地图相关变量
const mapLoaded = ref(false);
const trackPoints = ref([]);
const pi = 3.1415926535897932384626;

// 新增：解析轨迹数据
const parseTrackData = (data) => {
  if (!window.BMap) {
    console.error('BMap尚未初始化');
    return [];
  }
  // 1. WGS84转GCJ02 (火星坐标系)
  const wgs84togcj02 = (lng, lat) => {
    const a = 6378245.0;
    const ee = 0.00669342162296594323;
    let dlat = transformLat(lng - 105.0, lat - 35.0);
    let dlng = transformLng(lng - 105.0, lat - 35.0);
    const radlat = lat / 180.0 * pi;
    let magic = Math.sin(radlat);
    magic = 1 - ee * magic * magic;
    const sqrtmagic = Math.sqrt(magic);
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
    dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
    return { lng: lng + dlng, lat: lat + dlat };
  };

  // 坐标转换辅助函数
  const transformLat = (x, y) => {
    let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
    ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
    ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
    return ret;
  };

  const transformLng = (x, y) => {
    let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
    ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
    ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
    return ret;
  };

  // 2. GCJ02转BD09 (百度坐标系)
  const gcj02tobd09 = (lng, lat) => {
    const x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    const z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi);
    const theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi);
    return {
      lng: z * Math.cos(theta) + 0.0065,
      lat: z * Math.sin(theta) + 0.006
    };
  };

  // 3. 完整转换流程: WGS84 → GCJ02 → BD09
  const wgs84tobd09 = (lng, lat) => {
    const gcj = wgs84togcj02(lng, lat);
    return gcj02tobd09(gcj.lng, gcj.lat);
  };

  // 假设轨迹数据格式为 [[lng, lat], [lng, lat], ...]
  // 1. 完全移除轨迹数据 fallback 逻辑
  // 2. 仅当存在有效轨迹数据时才返回坐标点
  if (data?.geoPolylineDTO?.polyline?.length) {
    return data.geoPolylineDTO.polyline.map(point => {
      const converted = wgs84tobd09(point[0], point[1]);
      return new BMap.Point(converted.lng, converted.lat);
    });
  }
  // 无轨迹数据时返回空数组
  return [];
}

onMounted(async () => {
  // 动态加载html2canvas CDN
  const script = document.createElement('script');
  script.src = 'https://html2canvas.hertzen.com/dist/html2canvas.min.js';
  script.onload = () => console.log('html2canvas loaded successfully');
  script.onerror = () => {
    console.error('Failed to load html2canvas');
    alert('截图功能加载失败，请刷新页面重试');
  };
  document.head.appendChild(script);

  // 原有onMounted代码
  try {
    // 动态拼接文件名
    // const mainUrl = `/mock_json/${activityId}.json`
    // const splitsUrl = `/mock_json/${activityId}_splits.json`
    // const detailUrl = `/mock_json/${activityId}_details.json`
    const mainUrl = `/mock_json/${activityId}.json`
    const detailSplits = activityId==='default'?'':activityId
    const splitsUrl = `/mock_json/${detailSplits}splits.json`
    const detailUrl = `/mock_json/${detailSplits}details.json`

    const [mainRes, splitsRes, detailRes] = await Promise.all([
      fetch(mainUrl),
      fetch(splitsUrl),
      fetch(detailUrl)
    ])
    const mainData = await mainRes.json()
    const splitsData = await splitsRes.json()
    const detailData = await detailRes.json()

    // 合并分段详细数据
    const laps = splitsData.lapDTOs || []
    const details = detailData.lapDetails || []
    const mergedLaps = laps.map((lap, idx) => ({
      ...lap,
      ...(details[idx] || {})
    }))

    // 处理每公里数据
    lapData.value = mergedLaps.map(lap => ({
      duration: formatDurationShort(lap.duration || 0),
      pace: formatPace(lap.averageSpeed), // 应用配速格式化
      hr: lap.averageHR || '--',
      cadence: lap.averageRunCadence ? Math.round(lap.averageRunCadence) : '--',
      stride: lap.strideLength ? Math.round(lap.strideLength) : '--',
    }))

    // 2. 活动整体信息
    activityName.value = mainData.activityName
    description.value = mainData.description
    startTimeLocal.value = mainData.summaryDTO?.startTimeLocal || ''
    distance.value = mainData.summaryDTO?.distance || 0
    averageHR.value = mainData.summaryDTO?.averageHR || 0
    totalDuration.value = mainData.summaryDTO?.duration || 0
    totalDistance.value = mainData.summaryDTO?.distance || 0
    avgPace.value = formatPace(mainData.summaryDTO?.averageSpeed)
    bestPace.value = formatPace(mainData.summaryDTO?.maxSpeed)
    avgHr.value = mainData.summaryDTO?.averageHR || '--'
    maxHr.value = mainData.summaryDTO?.maxHR || '--'

    // 3. 分段数据（按lap）
    const paceData = mergedLaps.map(lap => {
      if (!lap.averageSpeed) return null;
      // 修正：结果除以10并限制最大值为9分钟
      const pace = (1000 / (lap.averageSpeed * 60)) / 10;
      return pace > 9 ? 9 : Number(pace.toFixed(2));
    })
    // 步频数据修正：确保数值在160左右
    const cadenceData = mergedLaps.map(lap => {
      const cadence = lap.averageRunCadence || 160; // 使用160作为默认值
      return cadence < 120 || cadence > 200 ? 160 : cadence; // 过滤异常值
    })
    const powerData = mergedLaps.map(lap => lap.averagePower || null)
    const hrData = mergedLaps.map(lap => lap.averageHR || null)
    const maxHrData = mergedLaps.map(lap => lap.maxHR || null)
    // 步幅取整处理
    const strideData = mergedLaps.map(lap => lap.strideLength ? Math.round(lap.strideLength) : null)

    // 计算累计时间
    let accTime = 0
    const labels = mergedLaps.map((lap, idx) => {
      const lapIdx = lap.lapIndex ?? idx + 1
      const duration = lap.duration || 0
      accTime += duration
      const durationStr = formatDurationShort(duration)
      const accTimeStr = formatDurationShort(accTime)
      return `第${lapIdx}圈\n${durationStr} (+${accTimeStr})`
    })

    // 4. 详细采样数据（每秒/每点）
    const detailKeys = [
      'directSpeed',         // 配速（m/s）
      'directHeartRate',     // 心率
      'directRunCadence',    // 步频
      'directStrideLength',  // 步幅
      'directPower'          // 功率
    ]
    const detailSeries = extractDetailSeries(detailData, detailKeys)
    const detailTimeLabels = (detailSeries.time || []).map(sec => formatDurationShort(sec))

    // 5. 详细采样数据用于更细腻的曲线
    const detailPaceData = (detailSeries.directSpeed || []).map(s => {
      if (!s) return null;
      // 修正：结果除以10并限制最大值为7分钟
      const pace = (1000 / (s * 60)) / 10;
      return pace > 9 ? 9 : Number(pace.toFixed(2));
    })
    // 详细步频数据修正
    const detailCadenceData = (detailSeries.directRunCadence || []).map(cadence => {
      return cadence ? Math.round(cadence*2) : null;
    })
    const detailPowerData = detailSeries.directPower || []
    const detailHrData = detailSeries.directHeartRate || []
    // 详细步幅取整
    const detailStrideData = detailSeries.directStrideLength.map(s => s ? Math.round(s) : null) || []

    paceW.value = window.innerWidth*.945
    window.onresize = e => {
      paceW.value = window.innerWidth*.945
    }
    // 6. 配速图表配置（lap+详细采样曲线叠加）
    paceOption.value = {
      backgroundColor: 'transparent',
      // 在tooltip的formatter中添加时间格式化逻辑
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const formatTime = (value) => {
            let minutes = Math.floor(value);
            let seconds = Math.round((value - minutes) * 60);
            // 处理秒数进位问题
            if (seconds === 60) {
              minutes += 1;
              seconds = 0;
            }
            return `${minutes}分${seconds}秒`;
          };
          
          // 处理每个series的数据
          // let result = params[0].axisValueLabel + '<br>';
          let result = '';
          params.forEach(param => {
            if(param.seriesName === '配速') {
              result += `${param.marker} ${param.seriesName}: ${formatTime(param.value)}<br>`;
            } else {
              result += `${param.marker} ${param.seriesName}: ${param.value}<br>`;
            }
          });
          return result;
        }
      },
      legend: { data: ['配速', '步频', '功率'], textStyle: { color: '#aaa' } }, // 删除了'配速(分段)'
      grid: { width: paceW, left: '0%', right: '-3%', bottom: '12%', top: '10%', containLabel: true },
      // grid: { width: window.innerWidth*.945, left: '0%', right: '0%', bottom: '12%', top: '10%', containLabel: true },
      // grid: { width: '100%', left: '0%', right: '-3%', bottom: '12%', top: '10%', containLabel: true },
      xAxis: [
        { // 分段
          type: 'category',
          data: labels,
          axisLine: { lineStyle: { color: '#555' } },
          axisLabel: { color: '#aaa' },
          axisTick: { show: false }
        },
        { // 详细
          type: 'category',
          data: detailTimeLabels,
          axisLine: { show: false },
          axisLabel: { show: false },
          axisTick: { show: false }
        }
      ],
      yAxis: [{
        type: 'value',
        inverse: true, // 配速越小越好，反转Y轴
        min: 3, // 设置合理的最小值
        max: 9, // 设置最大值为7分钟
        axisLabel: {
          color: '#aaa',
          formatter: value => {
            const min = Math.floor(value);
            // 修正：使用Math.round确保秒数取整
            const sec = Math.round((value - min) * 60);
            return `${min}:${sec.toString().padStart(2, '0')}`;
          }
        },
        splitLine: { lineStyle: { color: 'rgba(80, 80, 90, 0.5)' } },
        name: '配速            ',
        nameTextStyle: { color: '#aaa' }
      },
      { // 步频
        type: 'value',
        min: 90, max: 220, interval: 30, // 调整范围到150-170，聚焦160左右数据
        axisLabel: { color: '#aaa', formatter: '{value} 步/分' },
        splitLine: { show: false },
        axisLine: { lineStyle: { color: '#555' } },
        name: '步频', nameTextStyle: { color: '#aaa' }
      },
      { // 功率
        type: 'value',
        min: 200, max: 820, interval: 50,
        axisLabel: { color: 'transparent', formatter: '{value} W' },
        splitLine: { show: false },
        axisLine: { lineStyle: { color: '#555' } },
        name: '功率', nameTextStyle: { color: '#aaa' }
      }
      ],
      series: [
        // 删除了'配速(分段)'系列
        {
          name: '配速',
          type: 'line',
          xAxisIndex: 1,
          yAxisIndex: 0,
          data: detailPaceData,
          smooth: true,
          symbol: 'none',
          lineStyle: { width: 1, color: '#3b82f6' }, // 修改为实线蓝色
          emphasis: { focus: 'series' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0,  // 从顶部开始
              x2: 0,
              y2: 1,  // 到底部结束
              colorStops: [
                { offset: 0, color: 'rgba(59,130,246,0.5)' },  // 顶部深色
                { offset: 1, color: 'rgba(59,130,246,0)' }    // 底部透明
              ]
            },
            origin: 'end'  // 从曲线起点开始填充
          }
        },
        {
          name: '步频',
          type: 'line',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: detailCadenceData,
          smooth: true,
          symbol: 'none',
          lineStyle: { width: 1, color: 'rgba(245, 158, 66, .2)' }
        },
        {
          name: '功率',
          type: 'line',
          xAxisIndex: 1,
          yAxisIndex: 2,
          data: detailPowerData,
          smooth: true,
          symbol: 'none',
          lineStyle: { width: 1, color: 'rgba(16, 185, 129, .2)' }
        }
      ]
    }

    // 7. 心率图表配置（lap+详细采样曲线叠加）
    hrOption.value = {
      backgroundColor: 'transparent',
      tooltip: { trigger: 'axis' },
      legend: { data: ['心率(详细)', '最大心率', '步幅'], textStyle: { color: '#aaa' } },
      grid: { width: '99%', left: '0px', right: '0px', bottom: '12%', top: '10%', containLabel: true },
      xAxis: [
        { type: 'category', data: labels, axisLine: { lineStyle: { color: '#555' } }, axisLabel: { color: '#aaa' }, axisTick: { show: false } },
        { type: 'category', data: detailTimeLabels, axisLine: { show: false }, axisLabel: { show: false }, axisTick: { show: false } }
      ],
      yAxis: [
        { // 心率
          type: 'value',
          min: 50, max: 199, interval: 20, inverse: false,
          axisLabel: { color: '#aaa', formatter: '{value} bpm' },
          splitLine: { lineStyle: { color: 'rgba(80, 80, 90, 0.5)' } },
          axisLine: { lineStyle: { color: '#555' } },
          name: '心率', nameTextStyle: { color: '#aaa' }
        },
        { // 步幅
          type: 'value',
          min: 80, max: 180, interval: 20,
          axisLabel: { color: '#aaa', formatter: '{value} cm' },
          splitLine: { show: false },
          axisLine: { lineStyle: { color: '#555' } },
          name: '步幅', nameTextStyle: { color: '#aaa' }
        },
        // { // 步频  // <-- 修复：添加逗号分隔数组元素
        //   type: 'value',
        //   min: 140, max: 200, interval: 10,
        //   axisLabel: { color: '#aaa', formatter: '{value} spm' },
        //   splitLine: { show: false },
        //   axisLine: { lineStyle: { color: '#555' } },
        //   name: '步频', nameTextStyle: { color: '#aaa' }
        // }
      ],
      series: [
        {
          name: '心率(详细)',
          type: 'line',
          xAxisIndex: 1,
          yAxisIndex: 0,
          data: detailHrData,
          smooth: true,
          symbol: 'none',
          lineStyle: { width: 1, color: '#ef4444' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(239, 68, 68, 0.5)' },
                { offset: 1, color: 'rgba(239, 68, 68, 0.1)' }
              ]
            }
          }
        },
        {
          name: '最大心率',
          type: 'line',
          xAxisIndex: 0,
          yAxisIndex: 0,
          data: maxHrData,
          smooth: true,
          symbol: 'diamond',
          symbolSize: 6,
          lineStyle: { width: 1, color: 'rgba(251, 191, 36, .2)' },
          itemStyle: { color: 'rgba(251, 191, 36, .2)', borderWidth: 1, borderColor: 'rgba(229, 231, 235, .2)' }
        },
        {
          name: '步幅',
          type: 'line',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: detailStrideData,
          smooth: true,
          symbol: 'none',
          lineStyle: { width: 1, color: 'rgba(59, 130, 246, .2)' }
        }
      ]
    }

    try {

      // 新增：加载百度地图API
      const loadBaiduMap = () => {
        const myAK = '3jSBH5LxAsBWyjOVqNdJ6ZQtTpbYzs1i'
        return new Promise((resolve, reject) => {
          if (window.BMap) return resolve(window.BMap);
          
          const script = document.createElement('script');
          script.src = `https://api.map.baidu.com/api?v=3.0&ak=${myAK}&callback=initBaiduMap`;
          script.type = 'text/javascript';
          script.onerror = () => reject(new Error('百度地图API加载失败'));
          document.head.appendChild(script);
          
          window.initBaiduMap = () => {
            resolve(window.BMap);
          };
        });
      };
      
      const BMap = await loadBaiduMap();
      // 绘制轨迹 - 修改为
      trackPoints.value = parseTrackData(detailData);
      // 新增：无轨迹数据时隐藏地图模块
      if (trackPoints.value.length === 0) {
        isOutside.value = false;
        return
      }
      // 仅当有轨迹数据时才初始化地图
      const map = new BMap.Map('baidu-map');
      
      // 新增：解析轨迹数据
      map.enableScrollWheelZoom(true);
      
      // 新增：添加地图类型控件并设置地图类型
      map.addControl(new BMap.MapTypeControl({
        mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP]
      }));
      map.setMapType(BMAP_NORMAL_MAP);

      // 设置中心点和缩放级别
      const centerPoint = trackPoints.value[Math.floor(trackPoints.value.length / 2)];
      // map.centerAndZoom(centerPoint || new BMap.Point(116.404, 39.915), 15);
      map.centerAndZoom(new BMap.Point(116.404, 39.915), 15);
      map.enableScrollWheelZoom(true);
      
      // 绘制轨迹
      if (trackPoints.value.length > 1) {
        const polyline = new BMap.Polyline(trackPoints.value, {
          strokeColor: '#3b82f6',
          strokeWeight: 5,
          strokeOpacity: 0.8
        });
        map.addOverlay(polyline);
        
        // 添加起点终点标记
        map.addOverlay(new BMap.Marker(trackPoints.value[0]));
        map.addOverlay(new BMap.Marker(trackPoints.value[trackPoints.value.length - 1]));
      }

      // 加载轨迹数据 (假设从default_details.json获取)
      // const trackResponse = await fetch('/mock_json/default_details.json');
      // const trackData = await trackResponse.json();
      // trackPoints.value = parseTrackData(trackData);
      trackPoints.value = {};
    } catch (error) {
      console.error('地图初始化失败:', error);
      isOutside.value = false
    }
  } catch (error) {
      console.error('读取 JSON 文件出错:', error)
    }
  })

// 添加截屏功能
const captureScreenshot = () => {
  if (!window.html2canvas) {
    alert('截图功能正在加载，请稍候...');
    return;
  }

  // 显示加载提示
  const loading = document.createElement('div');
  loading.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);padding:20px;background:rgba(0,0,0,0.7);color:white;border-radius:8px;z-index:9999';
  loading.textContent = '正在截取屏幕...';
  document.body.appendChild(loading);

  // 使用setTimeout确保加载提示显示后再隐藏并截图
  // setTimeout(() => {
    // 隐藏加载提示
     loading.style.display = 'none';

     // 等待DOM更新后再截图
  requestAnimationFrame(() => {
    // 使用html2canvas截取整个页面
    window.html2canvas(document.body, {
      scale: window.devicePixelRatio,
      // y: -100,
      useCORS: true,
      logging: false
    }).then(canvas => {
      document.body.removeChild(loading);
      const link = document.createElement('a');
      // link.download = `跑步数据截图_${new Date().toLocaleString().replace(/[/: ]/g, '-')}.png`;
      link.download = `running_${new Date().toLocaleDateString()}.png`;
      link.href = canvas.toDataURL('image/png');
      link.click();
    }).catch(err => {
      loading.style.display = 'block'; // 出错时重新显示加载提示
      setTimeout(() => {
        document.body.removeChild(loading);
      }, 1000);
      console.error('截图失败:', err);
      alert('截图失败，请重试');
    });
  });
  // }, 500); 
};

</script>

<style scoped>
.bg-gray-750 {
  background-color: #2d3748;
}
/* .map-container {
  margin-top: 20px;
  padding: 15px;
} */
.map-view {
  width: 100%;
  height: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>


